﻿#region 命名空间

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ServiceModel;

#endregion

namespace Sharp.Infrastructure.Communication
{
    /// <summary>
    ///     表示Channel Factory管理器。
    /// </summary>
    internal sealed class ChannelFactoryManager : DisposableObject
    {
        #region 私有字段

        private static readonly ConcurrentDictionary<Type, ChannelFactory> Factories =
            new ConcurrentDictionary<Type, ChannelFactory>();

        public static readonly ChannelFactoryManager Instance = new ChannelFactoryManager();

        #endregion

        #region 构造函数

        static ChannelFactoryManager()
        {
        }

        private ChannelFactoryManager()
        {
        }

        #endregion

 

        #region Protected Methods

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                foreach (Type type in Factories.Keys)
                {
                    ChannelFactory factory = Factories[type];
                    try
                    {
                        factory.Close();
                    }
                    catch
                    {
                        factory.Abort();
                    }
                }
                Factories.Clear();
            }
        }

        #endregion

        #region 方法

        /// <summary>
        ///     获取与指定服务契约类型相关的Channel Factory实例。
        /// </summary>
        /// <typeparam name="T">服务契约的类型。</typeparam>
        /// <returns>与指定服务契约类型相关的Channel Factory实例。</returns>
        public ChannelFactory<T> GetFactory<T>() where T : class, IApplicationServiceContract
        {
            var factory = Factories.GetOrAdd(typeof (T), x =>
            {
                return new ChannelFactory<T>(typeof(T).Name);
            });

            //factory.Open();

            return factory as ChannelFactory<T>;

        }

        #endregion
    }
}